/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011      Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
 
http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.cpp;

import org.cocos2dx.lib.Cocos2dxActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.weibo.game.sdk.SinaGameSDKNative;
import com.weibo.game.sdk.WeiboGameSDKAPI;
import com.weibo.game.sdk.callback.SinaGameCallBack;
import com.weibo.game.sdk.callback.SinaUser;

@SuppressLint("HandlerLeak")
public class AppActivity extends Cocos2dxActivity {
	private static final String TAG = "AppActivity";
	private static AppActivity s_instance;
	
	//sdk回调状态码
    private static final int SINA_SDK_START = 0;
    private static final int SINA_SDK_SUCCESS = 1;
    private static final int SINA_SDK_ERROR = 2;
    private static final int SINA_SDK_CANCEL = 3;
    
	//通知相关(java通知c++)
	private static final String NOTIFICATION_LOGIN_RESULT = "notification_login_result";
	private static final String NOTIFICATION_PAY_RESULT = "notification_pay_result";
	private static final String NOTIFICATION_EXIT_RESULT = "notification_exit_result";
	
	private static Handler mHandler;
	private final static int HANDLE_BLACK_SCREEN = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		//初始化微博sdk，必须在onCreate之前调用
		WeiboGameSDKAPI.init(this);
		super.onCreate(savedInstanceState);
		
		s_instance = this;
		mHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				// 处理黑屏
				case HANDLE_BLACK_SCREEN:
					handleBlackScreen();
					break;
					
				default:
					break;
				}
			}
		};
	}
	
	public static void sdkLogin() {
		WeiboGameSDKAPI.login(s_instance, new SinaGameCallBack() {
			@Override
			public void onResult(int code, final Object obj) {
				final String json;
				Log.d(TAG, "sdkLogin-onResult(): code = " + code + ", " + obj.toString());
				if (code == SINA_SDK_SUCCESS) {
					//成功
					SinaUser user = (SinaUser) obj;
					json = user.toString();//直接调用obj.toString()也能得到SinaUser对象的json数据
					//此处演示直接将json数据传递给c++端，实际游戏里可以组合code+json的字符串进行传递，c++里再手动分解成code、json两部分字符串
					//或者直接通过jni编写c++回调的形式，将code和json作为回调方法里的两个参数传递给c++
					postNotification(NOTIFICATION_LOGIN_RESULT, json);
				}else if (code == SINA_SDK_START){
					//登录开始（用作统计）
				}else if (code == SINA_SDK_ERROR){
					//登录失败
				}else if (code == SINA_SDK_CANCEL) {
					//登录取消
				}
			}
		});
		
		postHandleBlackScreenMsg();
	}
	
	/**
	 * 支付
	 * @param amount  支付金额（单位分）
	 * @param subject 支付标题
	 * @param desc 支付描述
	 */
	public static void sdkPay(long amount, String subject, String desc){
	    if(WeiboGameSDKAPI.isLogin(s_instance)){
	        WeiboGameSDKAPI.pay(s_instance, amount, subject, desc, new SinaGameCallBack() {
	            @Override
	            public void onResult(int code, Object obj) {
	                Log.d(TAG, "sdkPay-onResult(): code = " + code + ", " + obj.toString());
	                //此处为了简单演示，直接传递code给c++端，实际游戏里可以将json数据传给c++
	                postNotification(NOTIFICATION_PAY_RESULT, String.valueOf(code));
	                Toast.makeText(s_instance, "code:" + code + ",info:" + obj.toString(), Toast.LENGTH_SHORT).show();
	            }
	        });
	    }else{
	        sdkLogin();
	    }
	    
	}
	
	public static void sdkExit(){
		WeiboGameSDKAPI.exit(s_instance, new SinaGameCallBack() {
            @Override
            public void onResult(int code, Object obj) {
            	Log.d(TAG, "sdkExit-onResult(): code = " + code + ", " + obj.toString());
                //将code作为通知的消息体传给c++，让c++来退出游戏，或者直接在这里通过java代码退出游戏
                postNotification(NOTIFICATION_EXIT_RESULT, String.valueOf(code));
            }
        });
    }
	
	/**
	 * 发送通知
	 * 
	 * 为了演示方便，直接在这里通过cocosd-x的CCNotificationCenter类发送通知
	 * 将java数据传递给c++，实际游戏里可以通过回调来进行java与c++之间的消息传递
	 * @param key  消息key
	 * @param data  消息内容
	 */
	private static void postNotification(final String key, final String data){
		s_instance.runOnGLThread(new Runnable() {
			@Override
			public void run() {
				Log.d(TAG, "java-postNotification(): key = " + key + ", data = " + data);
				JavaCallCppHelper.postNotification(key, data);
			}
		});
	}
	
	/**处理部分手机锁屏后游戏黑屏的问题，例如小米3*/
	private static void postHandleBlackScreenMsg(){
		Message msg = new Message();
		msg.what = HANDLE_BLACK_SCREEN;
		mHandler.sendMessage(msg);
	}
	
	/**处理部分手机锁屏后游戏黑屏的问题，例如小米3*/
	private void handleBlackScreen() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				onResume();
			}
		}).start();
	}

    @Override
    public void onBackPressed() {
        sdkExit();
        
    }
	
	
	
}
